"""
@author: wangkang
@contact: wangkang@autobio.com.cn
@file: question_answer.py
@time: 2020/4/2 11:02
@desc: 
"""

from py2neo import Graph


class AnswerSearcher:
    def __init__(self):
        self.g = Graph(
            host="192.168.34.10",
            http_port=7474,
            user="neo4j",
            password="root")

    def answer_prettify(self, question_type, answers):
        """
        回复模板设计
        :param question_type:
        :param answers:
        :return:
        """
        final_answer = []
        if not answers:
            return ''
        if question_type == 'unit_apparance':
            subject = answers[0]['m.name']
            desc = [i['n.name'] for i in answers]
            final_answer = '{0}的故障有：{1}'.format(subject, '；'.join(list(set(desc))))

        elif question_type == 'ins_type_have':
            subject = answers[0]['m.name']
            desc = [i['n.name'] for i in answers]
            final_answer = '{0}设备包含的单元有{1}个，分别为：\n {2}'.format(subject, len(set(desc)), '；'.join(list(set(desc))))

        elif question_type == 'unit_method':
            subject = answers[0]['m.name']
            desc = [i['n.name'] for i in answers]
            final_answer = '对于{0}，可以考虑以下维护策略：{1}'.format(subject, '；'.join(list(set(desc))))

        elif question_type == 'unit_have':
            subject = answers[0]['n.name']
            desc = [i['m.name'] for i in answers]
            final_answer = '{0} 包括以下子单元：{1}'.format(subject, '；'.join(list(set(desc))))

        elif question_type == 'sub_unit_belong':
            subject = answers[0]['m.name']
            desc = [i['n.name'] for i in answers]
            final_answer = '{0} 属于{1}单元'.format(subject, '；'.join(list(set(desc))))

        elif question_type == 'method_apply':
            subject = answers[0]['n.name']
            desc = [i['m.name'] for i in answers]
            final_answer = '{0}这种维护手段，可以用在以下单元：{1}'.format(subject, '；'.join(list(set(desc))))

        elif question_type == 'appear_on':
            subject = answers[0]['n.name']
            desc = [i['m.name'] for i in answers]
            final_answer = '{0} 经常出现在以下单元：{1}'.format(subject, '；'.join(list(set(desc))))
        return final_answer

    def search_main(self, sqls):
        """
        执行cypher查询，并返回相应结果
        :param sqls: cypher查询脚本
        :return:
        """
        final_answers = []
        for sql_ in sqls:
            question_type = sql_['question_type']
            queries = sql_['sql']
            answers = []
            for query in queries:
                ress = self.g.run(query).data()
                answers += ress
            final_answer = self.answer_prettify(question_type, answers)
            if final_answer:
                final_answers.append(final_answer)
        return final_answers
